package com.android.task5;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import com.google.android.maps.MyLocationOverlay;

import android.graphics.drawable.Drawable;
import android.util.Log;


public class FlickrManager {
	
	private final static String INFO_TAG = "Flickr Manager Info";	
	private final static String key = "af132e1981a446a441e273025b302f64";
	private final static String baseUrl = "http://api.flickr.com/services/xmlrpc/";
	private final static String getInfoTag = "flickr.photos.getInfo"; //not used, for getInfo we use XML-RPC
	private final static String requestMethod = "POST";
	//XML-RPC specification
	private final static String agent = "Frontier/5.1.2";
	private final static String contentType = "text/xml";
	private final static String host = "betty.userland.com";
	
	private FlickrRESTRequest mFlickrRequest;
	private FlickrRESTResponse mFlickrResponse;
	private FlickrXMLRPCRequest mFlickrXMLRPCRequest;
	private FlickrXMLRPCResponse mFlickrXmlrpcResponse;
	private ArrayList<FlickrPhoto> flickrPhotos;
	
	private int iterator;
	
	FlickrPhoto photo;

	
	public FlickrManager() {
		mFlickrRequest = new FlickrRESTRequest();
		mFlickrResponse = new FlickrRESTResponse();
		mFlickrXMLRPCRequest = new FlickrXMLRPCRequest();
		mFlickrXmlrpcResponse = new FlickrXMLRPCResponse();
		flickrPhotos = new ArrayList<FlickrPhoto>();
		iterator = 0;
	}
	
	public void getXMLResponseForBoungindBox(BoundingBox bbox){
		String searchUrl = mFlickrRequest.createStringURLForBoundingBox(bbox);
		URL newSearchURL;
		try {
			newSearchURL = new URL(searchUrl);
			URLConnection urlConn = newSearchURL.openConnection();
			InputStream is = urlConn.getInputStream();
			mFlickrResponse.parseRESTResponse(is);
			flickrPhotos = mFlickrResponse.getFlickrPhotos();
//			mFlickrXMLRPCRequest.sendInfoRequest(key, flickrPhotos.get(0).getPhotoId());
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void getXMLResponseForSearchTags(ArrayList<String> searchTags){
		String searchUrl = mFlickrRequest.createStringURLForSearchTags(searchTags);
		URL newSearchURL;
		try {
			newSearchURL = new URL(searchUrl);
			URLConnection urlConn = newSearchURL.openConnection();
			InputStream is = urlConn.getInputStream();
			mFlickrResponse.parseRESTResponse(is);
			flickrPhotos = mFlickrResponse.getFlickrPhotos();
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void sendInfoRequest(String apiKey, String photoId){
		URL infoUrl;
		HttpURLConnection urlc = null;
		String data = mFlickrXMLRPCRequest.createXMLRPCMessage(apiKey, photoId);
		char[] buffer = data.toCharArray();
		Log.i(INFO_TAG, data);
		try {
			infoUrl = new URL(baseUrl);
			
			urlc = (HttpURLConnection)infoUrl.openConnection();
			urlc.setRequestMethod(requestMethod);
			urlc.setDoOutput(true);
			urlc.setRequestProperty("Content-Type", contentType);
			urlc.setRequestProperty("User-Agent", agent);
			urlc.setRequestProperty("Content-Length",""+buffer.length);

		
			OutputStreamWriter osw = new OutputStreamWriter(urlc.getOutputStream());
			osw.write(buffer);
			osw.flush(); 
			// Get the response
			InputStream is = urlc.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			final StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null)
			{
			sb.append(line);
			}
			br.close();
//			Log.i(INFO_TAG, sb.toString());
			String output = sb.toString();
			mFlickrXmlrpcResponse.parseData(output);
			
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//			catch (SAXException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	
	public void displayUrlOfPhotosTODownload(){
		for(int i=0; i<flickrPhotos.size(); i++){
			if(flickrPhotos.get(i) != null){
				flickrPhotos.get(i).getInfo();
			}
		}
	}
	
	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	
	public Drawable downloadImage(int i){
		
		String downloadUrl = flickrPhotos.get(i).getDownloadUrl();
		Drawable d = null;
		try {
			InputStream is = (InputStream) this.fetch(downloadUrl);
			 d = Drawable.createFromStream(is, "src");
			return d;
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d;
		
	}
	
	public void setInfoForPhoto(FlickrPhoto mFlickrPhoto){

		this.photo = mFlickrPhoto;
		infoRequestThread irt = new infoRequestThread(mFlickrPhoto);
		new Thread(irt).start();
		photo.setTitle(mFlickrXmlrpcResponse.getTitle());
		photo.setAuthorRealName(mFlickrXmlrpcResponse.getRealname());
		photo.setAuthorUserName(mFlickrXmlrpcResponse.getUsername());


	}
	
	public Drawable getNextPhoto(){
		Drawable d = downloadImage(iterator);
		iterator++;
		return d;
	}
	
	public ArrayList<FlickrPhoto> getFlickrPhotos(){
		return flickrPhotos;
	}

	private class infoRequestThread implements Runnable{
		private FlickrPhoto mFlickrPhoto;
		
		public infoRequestThread(FlickrPhoto photo ){
			this.mFlickrPhoto = photo;
			
		}
		public void run() {
			
			Log.i("http","photoId: "+this.mFlickrPhoto.getPhotoId());
			sendInfoRequest(key, this.mFlickrPhoto.getPhotoId());
			
		}
	}
	
	
}
